<?php
/**
 * 会员中心
 * User: chen guang
 * Date: 2017/9/29 9:00
 *
 */

namespace app\admin\controller;
use app\admin\controller\Export;
use app\admin\controller\System;
use think\Db;
use think\Page;

class Merchant extends Common{

    /*
    *	构造函数
    */
    function __construct(){
        parent::__construct();

    }

    /**
     * 商户列表
     */
    public function index(){
        $status=input("status");
        if($status!=''){
            $where['status']=$status;
        }else{
            $where['status']=array('gt',-2);
        }
        $type=input("type");
        if($type!=''){
            $where['type']=$type;
        }
        if(input("keyword")){
            $where['nickname|mobile']=array("like",'%'.input('keyword').'%');
        }
        if(input("export")){
            $this->export($where);exit;
        }
        $db_shop=db("shop");
        $list = $db_shop->where($where)->order("sort desc,id desc")->paginate(10);
        $count =$db_shop->where($where)->order("id desc")->count();
        $this->assign('list',$list);
        $this->assign('count',$count);
        $this->assign('status',input("status"));
        $this->assign('type',input("type"));
        $this->assign('keyword',input("keyword"));
        return $this->fetch();
    }

    /**
     * 添加商户
     */
    public function  add_merchant(){

        if(request()->isPost()){
            $input = input();
            unset($input['admin/Merchant/add_merchant_html']);

            $file_array = [
                'id_positive',
                'id_reverse',
                'id_hold',
                'license',
                'foodlicense'
            ];

            foreach ($file_array as $value){
                $file = request()->file($value);
                if ($file) {
                    $info = $file->move('./static/uploads');
                    if ($info) {
                        $input[$value] = '/'.$info->getSaveName();
                    }
                }
            }

            $input['cid'] = 1;
            $input['isopen'] = '1';
            $input['is_home'] = '1';
            $input['status'] = '1';
            $input['password'] = md5('123456');

            $shop = db('shop')->where('mobile',$input['mobile'])->find();
            if(!empty($shop))return ['bool'=>0,'message'=>'该手机号已注册过商家!'];

            db('shop')->insert($input);
            return ['bool'=>'1'];
        }

        return $this->fetch();
    }

    public function  set_translation(){
        $ids = input('ids/a');
        $type = input('type');

        $where['id'] = ['in',$ids];
        $bool = db('shop')->where($where)->update(['is_mention'=>$type]);
        if($bool){
            echo '1';
        }else{
            echo '0';
        }
    }

    /**
     * 商户详情
     */
    public function detail(){
        $where['id']=input("id");
        $where['status']=array("gt",-2);
        $db_shop=db("shop");
        $list = $db_shop->where($where)->find();
        if($list['updateimages']) {
            $list['updateimages'] = unserialize($list['updateimages']);
        }
        $this->assign('data',$list);
        return $this->fetch();
    }
    /**
     * 商户统计
     */
    public function statis(){
        $shop_id= input('id');
        $db_goods=db("goods");
        $db_category_goods=db("category_goods");
        $data['shop_id']=$shop_id;
        $p=input('page','1');
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $goods=$db_goods->where($data)->page($p,$size)->order("id desc")->select();
        $db_order=db("order");
        foreach($goods as &$v){
            $v['image']=IMG_PATH.$v['image'];
            $or['og.goods_id'] = $v['id'];
            $or['o.status'] = '3';
            $or['o.finish_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
            $v['mon_ordernum'] = $db_order->alias("o")
                ->join("order_goods og","og.order_id=o.id")
                ->where($or)->count();
            $or['o.finish_time'] = array('between', [time() - 7 * 24 * 60 * 60, time()]);
            $v['week_ordernum'] = $db_order->alias("o")
                ->join("order_goods og","og.order_id=o.id")
                ->where($or)->count();
            $or['o.finish_time'] = array('between', [time() - 24 * 60 * 60, time()]);
            $v['day_ordernum'] = $db_order->alias("o")
                ->join("order_goods og","og.order_id=o.id")
                ->where($or)->count();
        }
        $category=$db_category_goods->select();
        $count=$db_goods->where($data)->count();
        $result['list'] = $goods;
        $result['count'] = $count;;
        $result['page_num']=$p;
        $result['page_limit']=$size;

        $goods=$result;
        $page=new Page($goods['count'],$goods['page_limit']);
        $goods['page'] = $page;
        $this->assign("data",$goods);
        $this->assign("page",$page);
        $this->assign("status",input('status'));
        $this->assign("cid",input('cid'));
        $this->assign("category",$category);
        $this->assign("name",input('name'));
        return $this->fetch();
    }
    /**
     * 菜品统计
     */
    public function variety(){
        $time = time();

        $p=input('page','1');
        $pageParam = [];
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $shopid=input('shopid');
        $goods_name=input('goods_name');
        $shopid_where = '';
        $goods_where = '';

        $page = ($p - 1)*$size;

        if(!empty($shopid)){
            $shopid_where .= "AND jo.shop_id={$shopid}";
            $pageParam['shopid'] = $shopid;
        }

        if(!empty($goods_name)){
            $goods_where .= "AND jg.name like '%{$goods_name}%'";
            $pageParam['goods_name'] = $goods_name;
        }

        $count = db()->query("SELECT count(id) as id_count from jdw_goods jg WHERE jg.`status` = 1 $goods_where");

        $goods = db()->query("SELECT jg.id, jg.name, jg.image , ( SELECT SUM(og.goods_num * og.goods_price) FROM jdw_order jo INNER JOIN jdw_order_goods og ON jo.id = og.order_id WHERE jo.`status` IN ('1', '2', '3') AND og.goods_id = jg.id {$shopid_where}) AS price_sales , ( SELECT SUM(og.goods_num) FROM jdw_order jo INNER JOIN jdw_order_goods og ON jo.id = og.order_id WHERE (jo.`status` IN ('1', '2', '3') AND og.goods_id = jg.id AND DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= jo.create_time) {$shopid_where} ) AS mone_sales , ( SELECT SUM(og.goods_num) FROM jdw_order jo INNER JOIN jdw_order_goods og ON jo.id = og.order_id WHERE (jo.`status` IN ('1', '2', '3') AND og.goods_id = jg.id AND DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= jo.create_time) {$shopid_where} ) AS week_sales , ( SELECT SUM(og.goods_num) FROM jdw_order jo INNER JOIN jdw_order_goods og ON jo.id = og.order_id WHERE (jo.`status` IN ('1', '2', '3') AND og.goods_id = jg.id AND to_days(FROM_UNIXTIME(jo.create_time, '%Y-%m-%d')) = to_days(now())) {$shopid_where} ) AS now_sales FROM jdw_goods jg WHERE jg.`status` = 1 {$goods_where} order by jg.id desc limit {$page},{$size}");

        $page=new Page($count[0]['id_count'],$size,$pageParam);

        //查询商家列表
        $shop = db('shop')->field('shopname,id')->select();

        $this->assign('shop',$shop);
        $this->assign('shopid',$shopid);
        $this->assign('goods_name',$goods_name);
        $this->assign('goods',$goods);
        $this->assign('page',$page);
        $this->assign('count',$count[0]['id_count']);
        $this->assign('path_image',IMG_PATH);
        return $this->fetch();
    }
    /**
     * 商户导出excel
     */
    public function export($where)
    {

        $headArr = array("ID","姓名","手机号码","身份证号","店铺名称","省份","城市","区/县","街道","详细地址",'注册时间');
        $db_shop=db("shop");
        $list = $db_shop->where($where)->order("sort desc,id desc")->select();
        $data=array();
        foreach($list as $k => $v){
            $data[$k][] = $v['id'];
            $data[$k][] = $v['realname'];
            $data[$k][] = $v['mobile'];
            $data[$k][] = $v['idcard'];
            $data[$k][] = $v['shopname'];
            $data[$k][] = $v['province'];
            $data[$k][] = $v['city'];
            $data[$k][] = $v['county'];
            $data[$k][] = $v['street'];
            $data[$k][] = $v['address'];
            $data[$k][] = date("Y-m-d H:i",$v['create_time']);
        }
        $filename='商户列表-'.date("Y-m-d H:i:s");
        (new Export())->ImportExcel($filename,$headArr,$data);
    }
    /*
  * 设置审核商户，删除
  */
    public function check(){
        $id = input('id/d');
        $status=input("status/d");
        if(!in_array($status,array(0,1,-1,-2))){
            exit(json_encode('参数有误'));
        }
        $db_shop=db("shop");
        $data['status']=$status;
        $shop=$db_shop->where("id='$id'")->find();
        if($status==1) {
            if ($shop['islicense'] == 0 || $shop['issafetygrade']==0 || $shop['isid']==0) {
                exit(json_encode('请先审核营业执照，身份证，食品安全证书'));
            }
        }
        $res=$db_shop->where("id='$id'")->update($data);
        if($res){
            exit(json_encode(1));
        }else{
            exit(json_encode(0));
        }
    }
    /**
     * 身份证审核
     */
    public function isid(){
        $id = input('id/d');
        $status=input("status/d");
        if(!in_array($status,array(0,1,-1))){
            exit(json_encode(0));
        }
        $db_shop=db("shop");
        $data['isid']=$status;
        $res=$db_shop->where("id='$id'")->update($data);
        if($res){
            exit(json_encode(1));
        }else{
            exit(json_encode(0));
        }
    }
    /**
     * 营业执照
     */
    public function license(){
        $id = input('id/d');
        $status=input("status/d");
        $type=input("type/s");
        if(!in_array($status,array(0,1,-1))){
            exit(json_encode(0));
        }
        $db_shop=db("shop");
        $data[$type]=$status;
        $res=$db_shop->where("id='$id'")->update($data);
        if($res){
            exit(json_encode(1));
        }else{
            exit(json_encode(0));
        }
    }
    /**
     *   设置排序
     */
    public function sort(){
        $id = input('id/d');
        if(!$id){
            echo -1;exit;
        }
        $data['sort'] = floatval(input('num'));
        $res=db("shop")->where("id='$id'")->update($data);
        if($res===false) {
            echo -3;exit;
        }else{
            echo 1;
        }
    }
    /**
     *   推挤与取消
     */
    public function ishome(){
        $id = input('id/d');
        if(!$id){
            echo -1;exit;
        }
        $shop=db("shop")->where("id='$id'")->find();
        if($shop['ishome']==1){
            $data['ishome']=0;
        }else{
            $data['ishome']=1;
        }
        $res=db("shop")->where("id='$id'")->update($data);
        if($res===false) {
            echo -3;exit;
        }else{
            echo 1;
        }
    }

    /**
     *	佣金
     */
    public function commission_set(){
        $id = input('id/d');
        $commission = input('commission');

        $shop = db('shop')->where(['id'=>$id])->field('shopname,commission')->find();

        if(request()->isAjax()){
            if($commission > 5)$this->error('超过了百分5');

            $commission_rules['ip'] = get_client_ip();
            $commission_rules['commission'] = $commission;
            $commission_rules['creatime'] = time();

            $commission_rules_json = json_encode($commission_rules);

            $result = db('shop')->where(['id'=>$id])->update(['commission'=>$commission,'commission_rules'=>$commission_rules_json]);
            if(!$result)$this->error('修改失败');
            $this->success('修改成功!',url('merchant/index'));
        }

        $this->assign('shop',$shop);
        $this->assign('id',$id);
        return $this->fetch();
    }

    /**
     * 自提佣金
     */
    public function commission_mention(){
        $id = input('id/d');
        $commission = input('commission');

        $shop = db('shop')->where(['id'=>$id])->field('cmomission_mention,shopname')->find();

        if(request()->isAjax()){
            $result = db('shop')->where(['id'=>$id])->update(['cmomission_mention'=>$commission]);
            if(!$result)$this->error('修改失败');
            $this->success('修改成功!',url('merchant/index'));
        }

        $this->assign('shop',$shop);
        $this->assign('id',$id);
        return $this->fetch();
    }

    /**
     *设置店铺
     */
    public function set_shop_home(){
        $id = input('id/d');

        if(request()->isAjax()){
            db('shop')->where(['is_home'=>'1'])->update(['is_home'=>'-1']);
            db('shop')->where(['id'=>$id])->update(['is_home'=>'1']);
            $this->success('修改成功！',url('Merchant/index'));
        }
    }

    /**
     * 店铺设置
     */
    public function  set_index(){
        $id = input('id/d');

        $data=db("shop")->where("id=".$id)->find();
        $data['open_time']=unserialize($data['open_time']);
        $data['delivery_time']=unserialize($data['delivery_time']);
        $data['tell']=explode(",",$data['tell']);
        $this->assign("data",$data);
        $this->assign("shop_id",$id);
        return $this->fetch();
    }

    public function OpenTimeTpl(){
        echo	'<div style="margin-left: 100px;line-height: 40px">
      <a href="javascript:;" class="fa fa-move" title="拖动调整此显示顺序">移动</a>&nbsp;
      <a href="javascript:;" onclick="deleteParam1(this)"  style="margin-top:10px;" title="删除">删除</a>
    开始时间 <input name="starttime[]" type="text" style="width: 150px"  class="textbox textbox_295"  value=""/>
              结束时间 <input name="endtime[]" type="text" style="width: 150px"   class="textbox textbox_295" value=""/>
  </div>';
    }
    public function DeliveryTimeTpl(){
        echo	'<div style="margin-left: 100px;line-height: 40px">
      <a href="javascript:;" class="fa fa-move" title="拖动调整此显示顺序">移动</a>&nbsp;
      <a href="javascript:;" onclick="deleteParam1(this)"  style="margin-top:10px;" title="删除">删除</a>
    开始时间 <input name="de_starttime[]" type="text" style="width: 150px"  class="textbox textbox_295"  value=""/>
              结束时间 <input name="de_endtime[]" type="text" style="width: 150px"   class="textbox textbox_295" value=""/>
  </div>';
    }

    public function addTell()
    {
        echo	'<div style="margin-left: 100px;line-height: 40px" >
                  <a href="javascript:;" class="fa fa-move" title="拖动调整此显示顺序">移动</a>&nbsp;
                  <a href="javascript:;" onclick="deleteParam1(this)"  style="margin-top:10px;" title="删除">删除</a>
                  <input name="tell[]" type="text" style="width: 150px"  class="textbox textbox_295"  value=""/>
              </div>';
    }

    /**
     * 设置送餐电话
     */
    public function tell(){
        $result=(new System())->tell();
        if(isset($result['message'])){
            echo $result['message'];
        }else{
            echo 1;
        }
    }

    public function setopentime(){
        if(request()->isPost()){
            $shop_id = input('shop_id');
            $starttime=input("starttime/a");
            $endtime=input("endtime/a");
            $data=array();
            if(!empty($starttime)){
                $option=array();
                foreach($starttime as $k=>$v){
                    $option[$k]['starttime']=$v;
                    $option[$k]['endtime']=$endtime[$k];
                }
                $data['open_time']=serialize($option);
            }
            $res=db("shop")->where("id=".$shop_id)->update($data);
            if($res===false){
                echo 0;
            }else{
                echo 1;
            }
        }
    }

    public function setdeliverytime(){
        if(request()->isPost()){
            $shop_id = input('shop_id');
            $starttime=input("starttime/a");
            $endtime=input("endtime/a");
            $data=array();
            if(!empty($starttime)){
                $option=array();
                foreach($starttime as $k=>$v){
                    $option[$k]['starttime']=$v;
                    $option[$k]['endtime']=$endtime[$k];
                }
                $data['delivery_time']=serialize($option);
            }
            $res=db("shop")->where("id=".$shop_id)->update($data);
            if($res===false){
                echo 0;
            }else{
                echo 1;
            }
        }
    }

    /**
     * 开关店
     */
    public function open(){
        $result=(new System())->open();
        if(isset($result['message'])){
            echo $result['message'];
        }else{
            echo 1;
        }
    }

    /**
     * 设置店铺简介
     */
    public function des(){
        $result=(new System())->des();
        if(isset($result['message'])){
            echo $result['message'];
        }else{
            echo 1;
        }
    }

    /**
     * 设置开关预约
     */
    public function book(){
        $result=(new System())->book();
        if(isset($result['message'])){
            echo $result['message'];
        }else{
            echo 1;
        }
    }

    /**
     * 设置是否开启配送
     */
    public function send(){
        $result=(new System())->send();
        if(isset($result['message'])){
            echo $result['message'];
        }else{
            echo 1;
        }
    }

    /**
     * 设置店铺缩少起送
     */
    public function full_distribution(){
        $result=(new System())->full_distribution();
        if(isset($result['message'])){
            echo $result['message'];
        }else{
            echo 1;
        }
    }
}